package com.dly.hope.service.impl;

import com.alibaba.excel.EasyExcelFactory;
import com.dly.hope.constant.ExceptionConstant;
import com.dly.hope.constant.StaticConstant;
import com.dly.hope.dao.TemplateDao;
import com.dly.hope.excelhandle.EasyExcelLister;
import com.dly.hope.model.dto.TempDTO;
import com.dly.hope.modle.Template;
import com.dly.hope.repository.TemplateRepository;
import com.dly.hope.service.TemplateService;
import com.dly.hope.utils.ExceptionPropertiesUtil;
import io.vavr.control.Try;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author linyu.dai
 * @project myserve
 * @description
 * @creat 2022/11/4 14:57:05
 */
@Service
@Slf4j
public class TemplateServiceImpl implements TemplateService {

    @Resource
    private TemplateDao templateDao;

    @Resource
    private TemplateRepository templateRepository;

    @Override
    public void update(MultipartFile file) {
        Try.withResources(file::getInputStream)
                .of(is->{
                    templateRepository.deleteAll();
                    EasyExcelLister<TempDTO> easyExcelLister = new EasyExcelLister<>(TempDTO.class);
                    EasyExcelFactory.read(is, TempDTO.class, easyExcelLister).sheet().doRead();
                    saveData(easyExcelLister.getSaveDataLists());
                    return true;
                }).onFailure(e-> log.error(e.getClass().getSimpleName(), e)).getOrElseThrow(()-> ExceptionPropertiesUtil.getException(ExceptionConstant.IMPORT_ERROR));
    }

    public void saveData(List<TempDTO> tempDTOS){
        List<Template> lists = Lists.newArrayList();

        tempDTOS.forEach(dto->{
            Template template = new Template();
            template.setId(dto.getId());
            template.setTemplate(dto.getTemplate());
            template.setType(dto.getType());
            template.setSubject(dto.getSubject());
            lists.add(template);
        });
        templateRepository.saveAll(lists);
    }

    @Override
    public void download(HttpServletResponse response) {
        Try.withResources(response::getOutputStream, () -> this.getClass().getClassLoader().getResourceAsStream("templates/temp.xlsx"))
                .of((os, is) -> {
                    List<TempDTO> tempDTOs = templateDao.getAll();
                    response.setContentType(StaticConstant.EXCEL_MEDIA_TYPE);
                    EasyExcelFactory.write(os).withTemplate(is).sheet().doFill(tempDTOs);
                    return true;
                }).onFailure(e-> log.error(e.getClass().getSimpleName(), e)).getOrElseThrow(()-> ExceptionPropertiesUtil.getException(ExceptionConstant.DOWNLOAD_ERROR));
    }
}
